package com.questetra.bpms.example.select.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import com.google.appengine.repackaged.com.google.common.base.Predicate;
import com.google.appengine.repackaged.com.google.common.collect.Iterables;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
import com.questetra.bpms.example.select.model.Country;

public class CountryService {
    public List<Country> list(Locale locale) {
        String[] isoCountries = Locale.getISOCountries();
        List<Country> countries = new ArrayList<Country>();
        for (int i = 0; i < isoCountries.length; i++) {
            String code = isoCountries[i];
            Country country =
                new Country(code, new Locale("", code)
                    .getDisplayCountry(locale));
            countries.add(country);
        }
        return countries;
    }

    public List<Country> query(String query, Locale locale) {
        final String converted = query.trim().toLowerCase();
        Iterable<Country> filtered =
            Iterables.filter(list(locale), new Predicate<Country>() {
                public boolean apply(Country country) {
                    if (country.getCode().toLowerCase().contains(converted)
                        || country.getName().toLowerCase().contains(converted)) {
                        return true;
                    }
                    return false;
                }
            });

        return Lists.newArrayList(filtered);
    }

    public List<Country> query(final String[] values, Locale locale) {
        Arrays.sort(values);
        Iterable<Country> filtered =
            Iterables.filter(list(locale), new Predicate<Country>() {
                public boolean apply(Country country) {
                    return Arrays.binarySearch(values, country.getCode()) >= 0;
                }
            });

        return Lists.newArrayList(filtered);
    }
}